package com.md.youyouhui.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityOilReceiveBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.response.GetAddressResponse;
import com.md.youyouhui.net.response.GetCardNumResponse;
import com.md.youyouhui.net.response.WxPayResponse;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.ui.pay.AuthResult;
import com.md.youyouhui.ui.pay.PayResult;
import com.md.youyouhui.ui.shopping.AddressMangerActivity;
import com.md.youyouhui.utils.DialogLoginUtils;
import com.md.youyouhui.utils.SharedPreferencesUtils;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * Created by AdministratorZJ
 * on 2019/4/29.
 */
public class ReceiveOilActivity extends BaseActivity {
    private ActivityOilReceiveBinding receiveBinding;
    private String id, couponId;
    private String phone, name, area, minute, code, money, month, allPrice;
    private MainViewModel viewModel;
    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ct, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ct, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(ct, "授权成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(ct, "授权失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    private IWXAPI msgApi;
    private String addressId;
    private String token;

    @Override
    public void setContentLayout() {
        receiveBinding = DataBindingUtil.setContentView(this, R.layout.activity_oil_receive);
        viewModel = new MainViewModel();
    }

    @Override
    public void initView() {
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorAccent));
        setSupportActionBar(receiveBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void initData() {
        token = SharedPreferencesUtils.getString(this, Constants.USER_TOKEN, "");
        msgApi = WXAPIFactory.createWXAPI(this, null);
        // 将该app注册到微信
        msgApi.registerApp(Constants.WXKEY);
        receiveBinding.receiveName.setText("点击卡片添加领取地址");
        receiveBinding.receiveAddress.setVisibility(View.GONE);
        receiveBinding.receiveAddressCard.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(this);
                return;
            }
            startActivityForResult(new Intent(ct, AddressMangerActivity.class), 100);
        });
        receiveBinding.meal.setOnClickListener(v -> startActivityForResult(new Intent(ct, MealOilActivity.class), 101));
        receiveBinding.receiveBtn.setOnClickListener(v -> {
            if (TextUtils.isEmpty(token)) {
                new DialogLoginUtils().dialogLogin(this);
                return;
            }
            receiveCard();
        });
        receiveBinding.shiyou.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // receiveBinding.shiyou.setButtonDrawable(R.drawable.bg_select);
                receiveBinding.shihua.setChecked(false);
                //receiveBinding.shihua.setButtonDrawable(R.drawable.bg_unselect);
                Toast.makeText(ct, "中石油", Toast.LENGTH_SHORT).show();
            } else {
                //receiveBinding.shiyou.setButtonDrawable(R.drawable.bg_unselect);
            }
        });
        receiveBinding.shihua.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                //receiveBinding.shihua.setButtonDrawable(R.drawable.bg_select);
                receiveBinding.shiyou.setChecked(false);
                //receiveBinding.shiyou.setButtonDrawable(R.drawable.bg_unselect);
                Toast.makeText(ct, "中石化", Toast.LENGTH_SHORT).show();
            } else {
                //receiveBinding.shihua.setButtonDrawable(R.drawable.bg_unselect);
            }
        });
        getCardNum();
    }

    private void getCardNum() {
        viewModel.getCardNum().observe(this, getCardNumResponse -> {
            assert getCardNumResponse != null;
            switch (getCardNumResponse.status) {
                case LOADING:
                    receiveBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    receiveBinding.progress.setVisibility(View.GONE);
                    GetCardNumResponse data = getCardNumResponse.data;
                    if (null == data) {
                        return;
                    }
                    receiveBinding.shihuaNum.setText(String.format("剩余%s张", data.sinopec));
                    receiveBinding.shiyouNum.setText(String.format("剩余%s张", data.petrochina));
                    if ("0".equals(data.petrochina)) {
                        // receiveBinding.shiyou.setButtonDrawable(R.drawable.bg_zhongshiyou);
                        receiveBinding.shiyou.setEnabled(false);
                    } else {
                        //receiveBinding.shiyou.setButtonDrawable(R.drawable.bg_unselect);
                        receiveBinding.shiyou.setEnabled(true);
                    }
                    if ("0".equals(data.sinopec)) {
                        //receiveBinding.shihua.setButtonDrawable(R.drawable.bg_zhongshiyou);
                        receiveBinding.shihua.setEnabled(false);
                    } else {
                        //receiveBinding.shihua.setButtonDrawable(R.drawable.bg_unselect);
                        receiveBinding.shihua.setEnabled(true);
                    }
                    if ("0".equals(data.petrochina) && "0".equals(data.sinopec)) {
                        receiveBinding.receiveBtn.setBackgroundTintList(getResources().getColorStateList(R.color.card_hui));
                        receiveBinding.receiveBtn.setEnabled(false);
                    } else {
                        receiveBinding.receiveBtn.setEnabled(true);
                        receiveBinding.receiveBtn.setBackgroundTintList(getResources().getColorStateList(R.color.colorAccent));
                    }
                    break;
                case ERROR:
                    receiveBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(activity, getCardNumResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    int type = 0;

    private void receiveCard() {
        String address = receiveBinding.receiveAddress.getText().toString();
        if (TextUtils.isEmpty(receiveBinding.receiveAddress.getText().toString())) {
            Toast.makeText(ct, "请添加领取地址", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(receiveBinding.receiveMeal.getText().toString())) {
            Toast.makeText(ct, "请选择套餐", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!receiveBinding.shihua.isChecked() && !receiveBinding.shiyou.isChecked()) {
            Toast.makeText(ct, "请选择卡片类型", Toast.LENGTH_SHORT).show();
            return;
        }
        String price = receiveBinding.receiveAllPrice.getText().toString();
        //0 中石化 1 中石油
        if (receiveBinding.shihua.isChecked()) {
            type = 0;
        } else if (receiveBinding.shiyou.isChecked()) {
            type = 1;
        }
        if (TextUtils.isEmpty(money)) {
            return;
        }
        String[] split = allPrice.split("¥");
        showPayDialog(name, phone, area, minute, code, type, id, couponId, Integer.parseInt(money), split[1]);
    }

    private void showPayDialog(String name, String phone, String area, String minute, String code, int type, String id, String couponId, int money, String allPrice) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_pay, null);
        builder.setView(view);
        builder.setMessage("请选择支付方式");
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        ConstraintLayout aliPay = view.findViewById(R.id.aliPay);
        ConstraintLayout wxPay = view.findViewById(R.id.wxPay);
        aliPay.setOnClickListener(v -> {
            aliPayService(name, phone, area, minute, code, type, id, couponId, money, allPrice);
            alertDialog.dismiss();
        });
        wxPay.setOnClickListener(v -> {
            //Toast.makeText(this, "敬请期待", Toast.LENGTH_SHORT).show();
            wxPayService(name, phone, area, minute, code, type, id, couponId, money, allPrice);
            alertDialog.dismiss();
        });
    }

    private void aliPayService(String name, String phone, String area, String minute, String code, int type, String id, String couponId, int money, String allPrice) {
        viewModel.receiveCard(name, phone, area, minute, code, type, id, couponId, money, allPrice, "0").observe(this, stringResource -> {
            assert stringResource != null;
            switch (stringResource.status) {
                case LOADING:
                    receiveBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    receiveBinding.progress.setVisibility(View.GONE);
                    String data = (String) stringResource.data;
                    if (TextUtils.isEmpty(data)) {
                        Toast.makeText(ct, "获取支付orderInfo为null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    payAli(data);
                    break;
                case ERROR:
                    receiveBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(activity, stringResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void wxPayService(String name, String phone, String area, String minute, String code, int type, String id, String couponId, int money, String allPrice) {
        viewModel.receiveCard(name, phone, area, minute, code, type, id, couponId, money, allPrice, "1").observe(this, stringResource -> {
            assert stringResource != null;
            switch (stringResource.status) {
                case LOADING:
                    receiveBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    receiveBinding.progress.setVisibility(View.GONE);
                    Map<String, String> jsonObject = (Map<String, String>) stringResource.data;
                    if (null == jsonObject) {
                        Toast.makeText(ct, "获取支付wx_orderInfo为null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String appid = jsonObject.get("appid");
                    String partnerid = jsonObject.get("partnerid");
                    String prepayid = jsonObject.get("prepayid");
                    String packageValue = jsonObject.get("package");
                    String noncestr = jsonObject.get("noncestr");
                    String timestamp = jsonObject.get("timestamp");
                    String sign = jsonObject.get("sign");
                    WxPayResponse wxPayResponse = new WxPayResponse();
                    wxPayResponse.appid = appid;
                    wxPayResponse.partnerid = partnerid;
                    wxPayResponse.prepayid = prepayid;
                    wxPayResponse.packageValue = packageValue;
                    wxPayResponse.noncestr = noncestr;
                    wxPayResponse.timestamp = timestamp;
                    wxPayResponse.sign = sign;
                    wxAli(wxPayResponse);
                    break;
                case ERROR:
                    receiveBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(activity, stringResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void wxAli(WxPayResponse data) {
        PayReq request = new PayReq();
        request.appId = data.appid;
        request.partnerId = data.partnerid;
        request.prepayId = data.prepayid;
        request.packageValue = data.packageValue;
        request.nonceStr = data.noncestr;
        request.timeStamp = data.timestamp;
        request.sign = data.sign;
        msgApi.sendReq(request);
    }

    private void payAli(String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ReceiveOilActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //选择了其他地址，就不使用默认地址
        String token = SharedPreferencesUtils.getString(this, Constants.USER_TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            if (TextUtils.isEmpty(name)) {
                getDefault();
            }
        }
    }

    private void getDefault() {
        viewModel.getDefaultAddress().observe(this, getAddressResponse -> {
            assert getAddressResponse != null;
            switch (getAddressResponse.status) {
                case LOADING:
                    receiveBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    receiveBinding.progress.setVisibility(View.GONE);
                    GetAddressResponse data = getAddressResponse.data;
                    if (null == data) {
                        return;
                    }
                    if (TextUtils.isEmpty(data.mobilePhone)) {
                        receiveBinding.receiveName.setText("请添加收货地址");
                        receiveBinding.receiveAddress.setVisibility(View.GONE);
                    } else {
                        name = data.consignee;
                        phone = data.mobilePhone;
                        area = data.area;
                        minute = data.detailedAddress;
                        code = data.postcode;
                        addressId = data.id;
                        receiveBinding.receiveName.setText(String.format("%s\t\t\t%s", data.consignee, data.mobilePhone));
                        receiveBinding.receiveAddress.setVisibility(View.VISIBLE);
                        receiveBinding.receiveAddress.setText(String.format("%s%s", data.area, data.detailedAddress));
                    }
                    break;
                case ERROR:
                    receiveBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, getAddressResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (null == data) {
                return;
            }
            Bundle extras = data.getExtras();
            if (extras == null) {
                return;
            }
            GetAddressResponse address = (GetAddressResponse) extras.getSerializable("address");
            if (null == address) {
                return;
            }
            name = address.consignee;
            phone = address.mobilePhone;
            area = address.area;
            minute = address.detailedAddress;
            code = address.postcode;
            addressId = address.id;
            receiveBinding.receiveName.setText(String.format("%s\t\t\t%s", name, phone));
            receiveBinding.receiveAddress.setVisibility(View.VISIBLE);
            receiveBinding.receiveAddress.setText(String.format("%s%s", area, minute));
        } else if (requestCode == 101 && resultCode == RESULT_OK) {
            if (null == data) {
                return;
            }
            money = data.getStringExtra("money");
            month = data.getStringExtra("month");
            allPrice = data.getStringExtra("allPrice");
            String savePrice = data.getStringExtra("savePrice");
            id = data.getStringExtra("id");
            couponId = data.getStringExtra("couponId");
            receiveBinding.receiveAllPrice.setText(allPrice);
            receiveBinding.receiveMealPrice.setText(allPrice);
            receiveBinding.receiveSave.setText(savePrice);
            receiveBinding.receiveMeal.setText(String.format("月充%s,%s个月", money, month));
        }
    }
}
